package com.xbongbong.paas.service.impl;

import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.PatternEnum;
import com.xbongbong.paas.help.PaasExcelExportHelp;
import com.xbongbong.paas.pojo.dto.ImportSmsDTO;
import com.xbongbong.paas.pojo.vo.ExcelTemplateVO;
import com.xbongbong.paas.pojo.vo.ImportSmsVO;
import com.xbongbong.paas.service.ExcelOperatorService;
import com.xbongbong.paas.service.HandleImportService;
import com.xbongbong.paas.service.SmsImportService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.sms.model.SmsConfigModel;
import com.xbongbong.pro.sms.pojo.SmsImportExcelResultPojo;
import com.xbongbong.saas.constant.export.ImportConstant;
import com.xbongbong.saas.domain.entity.SmsConfigEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 短信导入导出Service层
 *
 * @author wufeng
 * @date 2018/9/21 14:47
 */
@Service("smsImportService")
public class SmsImportServiceImpl implements SmsImportService {

    private static final Logger LOG = LoggerFactory.getLogger(SmsImportServiceImpl.class);

    @Resource
    private ExcelOperatorService excelOperatorService;
    @Resource
    private HandleImportService handleImportService;
    @Resource
    private SmsConfigModel smsConfigModel;

    @Override
    public ExcelTemplateVO getSmsTemplate(BaseDTO baseDTO) throws XbbException {
        ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
        try {
            Map<String, Object> tipMap = new HashMap<>(16);
            tipMap.put("columnCount", 2);
            tipMap.put("title", I18nMessageUtil.getMessage(ImportConstant.SMS_IMPORT_TITLE_WARNING));
            List<Map<String, Object>> titleList = new ArrayList<>();
            titleList.add(tipMap);
            List<List<Map<String, Object>>> moreTitleList = new ArrayList<>();
            moreTitleList.add(titleList);

            String[] colSecondTitle = new String[2];
            colSecondTitle[0] = I18nMessageUtil.getMessage(CommonConstant.CUSTOMER_NAME);
            colSecondTitle[1] = PatternEnum.MOBILE.getDesc();
            Workbook workbook = excelOperatorService.createEmptyExcel4MoreTitle(15, I18nMessageUtil.getMessage(I18nStringConstant.GROUP_SMS_TEMPLATE), colSecondTitle, moreTitleList);
            excelTemplateVO.setWorkbook(workbook);
            excelTemplateVO.setName(I18nMessageUtil.getMessage(I18nStringConstant.GROUP_SMS_TEMPLATE) + ImportConstant.EXCEL_SUFFIX);
        } catch (Exception e) {
            LOG.error("生成群发短信模版导入模板错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, e.getMessage());
        }
        return excelTemplateVO;
    }

    @Override
    public ImportSmsVO importSmsData(ImportSmsDTO importSmsDTO) throws XbbException {
        // 不能包含的特殊字符
        String[] shield = new String[]{"\\@", "\\#", "\\$", "\\%", "\\^", "\\&", "\\*", "\\￥", "\\{", "\\}", "｛", "｝", "\\[", "\\]", "【", "】"};

        Integer smsCounts = 0;
        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", importSmsDTO.getCorpid());
        param.put("del", 0);
        List<SmsConfigEntity> configLists = smsConfigModel.findEntitys(param);
        if (configLists.size() > 0) {
            SmsConfigEntity confEntity = configLists.get(0);
            smsCounts = confEntity.getSmsCount();
            if (Objects.isNull(smsCounts)) {
                smsCounts = 0;
            }
        }

        // 第一行是大标题 第二行是小标题 数据从第三行开始读取
        int rowDataStartIndex = ImportConstant.VALUE_STAR_ROW_INDEX;
        List<SmsImportExcelResultPojo> dataList = new ArrayList<>();
        //计算发送条数
        int sendCounts = 0;
        try {
            String content = Objects.toString(importSmsDTO.getContent(), "");
            InputStream fileInputStream = importSmsDTO.getFile().getInputStream();
            Workbook workBook = WorkbookFactory.create(fileInputStream);
            String[][] excelData = handleImportService.getExcelValue(workBook, 1);

            String msg;
            String row;
            String name;
            String mobile;
            //一条短信长度
            int oneLength;
            //一条长短信分为几条
            int oneCount;
            String contentTag = I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_HONOR);
            if (!content.contains(contentTag)) {
                //不含变量的模版
                if (!StringUtil.isEmpty(content)) {
                    oneLength = content.length();
                    if (oneLength > 70) {
                        oneCount = oneLength / 67;
                        //长短信67字一条,防止整除时多加1
                        oneCount += (oneLength % 67 == 0) ? 0 : 1;
                    } else {
                        oneCount = 1;
                    }
                    sendCounts = oneCount * (excelData.length - rowDataStartIndex);
                }
            }

            for (int i = rowDataStartIndex; i < excelData.length; i++) {
                name = excelData[i][0];
                mobile = excelData[i][1];
                //计算本条短信长度，发送条数
                if (content.contains(contentTag)) {
                    //含变量的模版
                    String contentTem = content + name;
                    oneLength = contentTem.length() - contentTag.length();
                    if (oneLength > 70) {
                        oneCount = oneLength / 67;
                        //长短信67字一条,防止整除时多加1
                        oneCount += (oneLength % 67 == 0) ? 0 : 1;
                    } else {
                        oneCount = 1;
                    }
                    sendCounts += oneCount;
                }

                if (StringUtil.isEmpty(name)) {
                    msg = I18nMessageUtil.getMessage(I18nStringConstant.NAME_NOT_EMPTY);
                    row = String.format(I18nMessageUtil.getMessage(I18nStringConstant.LINE_ERROR), i+1);
                } else if (name.length() > 15) {
                    msg = I18nMessageUtil.getMessage(I18nStringConstant.NAME_EXCEEDS_LENGTH_LIMIT);
                    row = String.format(I18nMessageUtil.getMessage(I18nStringConstant.LINE_ERROR), i+1);
                } else if (StringUtil.keywordsShield(name, shield).contains("*")) {
                    msg = I18nMessageUtil.getMessage(I18nStringConstant.SPECIAL_CHARACTERS);
                    row = String.format(I18nMessageUtil.getMessage(I18nStringConstant.LINE_ERROR), i+1);
                } else if (!StringUtil.isMobile(mobile)) {
                    msg = I18nMessageUtil.getMessage(I18nStringConstant.WRONG_NUMBER);
                    row = String.format(I18nMessageUtil.getMessage(I18nStringConstant.LINE_ERROR), i+1);
                } else {
                    msg = "pass";
                    row = "";
                }

                SmsImportExcelResultPojo resultPojo = new SmsImportExcelResultPojo();
                resultPojo.setName(name);
                resultPojo.setMobile(mobile);
                resultPojo.setMsg(msg);
                resultPojo.setRow(row);
                dataList.add(resultPojo);
            }

            // 关闭流
            PaasExcelExportHelp.closeWorkBookException(workBook);

        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.UNRECOGNIZED_FILE);
        }

        ImportSmsVO importSmsVO = new ImportSmsVO();
        importSmsVO.setSmsCounts(smsCounts);
        importSmsVO.setSendCounts(sendCounts);
        importSmsVO.setDataList(dataList);
        return importSmsVO;
    }
}

